<template>
<div :class="[$style.container]">
  <div :class="[$style.header]" v-if="current">
    <div><doc-icon :data="current"></doc-icon><span class="ml-2">{{current.name}}</span></div>
    <div>
      <template v-if="!linkId">
        <el-button size="mini" @click="onEdit" v-if="canEdit">编辑</el-button>
        <el-button size="mini" @click="onDownload" v-if="canDownload">下载</el-button>
        <el-button size="mini" @click="onPrint" v-if="canPrint">打印</el-button>
        <el-link :underline="false" @click="expand = !expand" class="ml-3">
          <span class="ft-24" v-if="expand"><i class="el-icon-s-unfold"></i></span>
          <span class="ft-24" v-else><i class="el-icon-s-fold"></i></span>
        </el-link>
      </template>
    </div>
  </div>
  <div :class="[$style.body]">
    <div :class="[$style.main]">
      <div :class="[$style.content]">
        <iframe :src="src" frameborder="0" :class="[$style.iframe]" ref="iframe" v-if="src"></iframe>
        <empty-data v-else-if="!current">
          <span>加载中...</span>
        </empty-data>
        <empty-data v-else-if="unsupported">
          <template v-slot:icon><svg-icon icon="unsupported"></svg-icon></template>
          <span>不支持该类型文件预览</span>
        </empty-data>
        <empty-data v-else-if="unauthorized">
          <template v-slot:icon><svg-icon icon="unauthorized"></svg-icon></template>
          <span>你没有该文件的预览权限</span>
        </empty-data>
      </div>
      <div :class="[$style.footer]">
        <file-gallery :current.sync="current" :parent-id="parentId" :id="id" :versionId="versionId" :linkId="linkId" :accessCode="accessCode"></file-gallery>
      </div>
    </div>
    <div :class="[$style.aside]" v-if="expand && !linkId">
      <doc-panel :data="current"></doc-panel>
    </div>
  </div>

</div>
</template>

<script lang="ts">

import { download, preview, print, getUserDocs } from '@/api/doc'
import { Vue, Component, Provide, Watch, Ref, Prop } from 'vue-property-decorator'
import FileGallery from './components/file-gallery/index.vue'
import DocPanel from '@/views/pages/components/doc-panel/index.vue'
import { hasPerm, PermissionName } from '@/config/acl'
import { canEdit, canPreview, canPrint } from '@/config/content-type'
import { downloadFromUrl } from '@/utils/download'
import { AppModule } from '@/store'
import { expr } from '@/utils/url'
import { getDocLink, previewDoc } from '@/api/doc-share'
import { getInitOptions } from '@/config/init'
import { getWatermark } from '@/api/watermark'

@Component({
  components: { FileGallery, DocPanel }
})
export default class Preview extends Vue {
  @Prop(String) id!: string

  @Prop(String) parentId!: string

  @Prop(String) versionId!: string // 历史版本预览

  @Prop(String) linkId!: string // 外链预览

  @Prop(String) accessCode!: string // 外链提取码

  @Ref() iframe!: HTMLIFrameElement

  @AppModule.State properties!: any

  current: any = null

  // items: any[] = []

  src = ''

  unsupported = true

  unauthorized = true

  expand = true

  get previewUrl () {
    // return expr(this.properties?.deploy?.previewWeb || '') + '/preview'
    return getInitOptions().previewUrl + '/preview'
  }

  get onlyOfficeUrl () {
    return expr(this.properties?.deploy?.onlyOfficeWeb || '')
  }

  get canEdit () {
    return this.current && hasPerm('edit', this.current) && canEdit(this.current.name)
  }

  get canDownload () {
    return this.current && hasPerm('download', this.current)
  }

  get canPrint () {
    return this.current && hasPerm('print', this.current) && canPrint(this.current.name)
  }

  async genSrc () {
    if (!this.current) return ''
    this.src = ''
    this.unauthorized = !hasPerm('preview', this.current)
    this.unsupported = !canPreview(this.current?.name)
    if (this.unsupported || this.unauthorized) return
    const response = {}
    const previewRequest = this.versionId ? Promise.resolve(this.current?.url)
      : (this.linkId ? previewDoc(Number(this.linkId), this.current?.id, this.accessCode) : preview(this.current?.id))
    const link: any = await (this.linkId ? getDocLink(this.linkId as any, this.accessCode) : Promise.resolve(null))
    previewRequest.then(url => {
      this.$oss.signatureUrl(url, { response }).then(url => {
        const query = {
          src: url,
          encrypt: this.properties?.deploy?.encryptFile ? '1' : '0',
          userid: (link && link.creationBy) || this.$auth?.principle?.user?.id,
          username: (link && link.creationByName) || this.$auth?.principle?.user?.username,
          onlyOfficeUrl: this.onlyOfficeUrl,
          filename: this.current?.name
        }
        this.watermarkAttrs().then(({ watermarkDisabled, watermark }) => {
          if (watermark) Object.assign(query, { watermark })
          if (watermarkDisabled) Object.assign(query, { watermarkDisabled: 1 })
          const q = Object.entries(query).map(([k, v]) => {
            return encodeURIComponent(k) + '=' + encodeURIComponent(v)
          }).join('&')
          this.src = this.previewUrl + '?' + q
        })
      })
    })
  }

  watermarkAttrs () {
    const getDefault = () => {
      const watermarkDisabled = !!this.properties?.deploy?.watermarkDisabled
      const content = !watermarkDisabled && this.properties?.deploy?.watermark
      const ret: any = { watermarkDisabled }
      if (content) {
        ret.watermark = window.btoa(JSON.stringify({ content }))
      }
      return ret
    }
    const isEnt = this.current?.ownType === 'enterprise'
    if (!isEnt) return Promise.resolve(getDefault())
    return getWatermark(this.current?.ownId).then(data => {
      if (!data) return getDefault()
      if (!data?.enabled) {
        return { watermarkDisabled: true }
      } else {
        return {
          watermarkDisabled: false,
          watermark: encodeURIComponent(JSON.stringify(data))
        }
      }
    })
  }

  // loadItems () {
  //   if (!this.parentId) return
  //   getUserDocs({ page: 0, size: 100 }, Number(this.parentId)).then(data => {
  //     this.items = data?.content || []
  //   })
  // }

  onEdit () {
    this.$router.push(`/editor/${this.current?.id}`)
  }

  onDownload () {
    download(this.current?.id).then(url => {
      const response = {
        'content-disposition': `attachment; filename=${encodeURIComponent(this.current?.name)}`
      }
      this.$oss.signatureUrl(url, { response }).then(url => {
        downloadFromUrl(url)
      })
    })
  }

  onPrint () {
    if (!this.iframe) return
    if (this.iframe.contentWindow) {
      this.iframe.contentWindow.postMessage({ type: 'print' }, '*')
      print(this.current?.id)
    }
  }

  created () {
    // this.loadItems()
  }

  @Watch('current') currentChange () {
    this.genSrc()
  }
}
</script>

<style lang="scss" module>
@import "~@/styles/vars.scss";

$header-height: 36px;

.container {
}

.header {
  height: $header-height;
  box-shadow: 0 1px 4px rgba(0,21,41,.08);
  display: flex;
  justify-content: space-between;
  padding: 0 20px;
  align-items: center;
  border: 1px solid $border-split-color;
  box-sizing: border-box;
}

.body {
  display: flex;
  height: calc(100vh - #{$header-height});
}

.aside {
  flex: 0 0 auto;
  width: 300px;
}

.main {
  flex: 1 1 auto;
  display: flex;
  flex-direction: column;
}

.content {
  flex:  1 1 auto;
}

.footer {
  flex: 0 0 auto;
}

.iframe {
  width: 100%;
  height: 100%;
}
</style>
